import router from '@/router'
import store from '@/store'
import { refreshAccessToken } from 'api/api.js'
import { postRefreshToken } from 'api/http.js'
import { getExpires, getRefreshExpires } from '@/utils/auth'
import bus from './bus'

export const minExpTime = 1800 // 判断过期时间，小于 1800 时间刷新令牌
export const getExpiresTime = (type) => {
  // 判断访问令牌或刷新令牌的过期时间
  const expires = (type === 'refresh' ? getRefreshExpires() : getExpires()) || 0
  const nTime = new Date().getTime()
  const nTimeSecond = Math.floor(nTime / 1000)
  const expTime = expires - nTimeSecond
  // console.log('expTime', expTime)
  return expTime
}
const expiresCalculation = () => {
  // 接口请求时判断访问令牌是否过期，需要刷新
  const expTime = getExpiresTime()
  return new Promise(async (resolve, reject) => {
    // 客户端时间过期（7天）就退出界面
    if (expTime && expTime > minExpTime) {
      resolve(true)
    } else if (expTime && expTime > 1) {
      refreshAccessToken().then((res) => {
        if (res && res.code === 10000) {
          const cont = res.content
          store.dispatch('user/setNewTokenInfo', cont)
        }
        resolve(true)
      }).catch(()=>{
        reject()
      })
    } else {
      const refreshRes = await postRefreshToken()
      if (refreshRes) {
        resolve(true)
      } else {
        bus.$message.warning('令牌过期，请重新登录！')
        await store.dispatch('user/logout')
        router.push('/login')
        reject()
      }
    }
  })
}

export default expiresCalculation
